package com.helloandroid.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.R
import com.helloandroid.activitys.HeShuiDaKaActivity
import com.helloandroid.tools.BitmapMemCache
import com.helloandroid.tools.MyLog

class HeShuiProgress @JvmOverloads constructor(
        ctx: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
) : View(ctx, attrs, defStyle) {

    val heShuiActivity:HeShuiDaKaActivity = ctx as HeShuiDaKaActivity

    interface ISelected {
        // 这里的 idx 是从0 开始的
        fun selected(idx: Int)
    }

    companion object {
        const val ICON_COUNT = 8
        const val DotSize = 18

        const val UNCOMPLETE = 1
        const val COMPLETED = 2
        const val LOCKED = 3
        const val CURRENT_ENABLE = 4
    }

    var bgWidth = 0f
    var bgHeight = 0f
    var center = PointF()
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val dotOyDp = resources.getDimension(R.dimen.dp5)

    lateinit var bgDst: RectF
    lateinit var bgSrc: Rect

    lateinit var progressBitmap: Bitmap
    lateinit var uncompleteBitmap: Bitmap
    lateinit var completedBitmap: Bitmap
    lateinit var lockedBitmap: Bitmap
    lateinit var currentEnableBitmap: Bitmap

    lateinit var dotBitmap: Bitmap

    private val bitmapList = arrayListOf<Bitmap>()
    private val lstTouchRect = arrayListOf<RectF>()

    // 当前选中的
    var selectedIdx = -1
    var selectedCallback: ISelected? = null

    init {
        init()
    }

    private fun init() {
        val dm = AppUtil.dm
        val width = dm.widthPixels
        val height = resources.getDimension(R.dimen.dp50)
        bgWidth = width * 0.8f
        bgHeight = resources.getDimension(R.dimen.dp10)
        center.set(width / 2.0f, height / 2.0f)

        loadBitmap()

        for (i in 0 until ICON_COUNT) {
            bitmapList.add(uncompleteBitmap)
            lstTouchRect.add(RectF())
        }
        val left: Float = (width - bgWidth) / 2.0f
        val top: Float = (height - bgHeight) / 2.0f
        bgSrc = Rect(0, 0, progressBitmap.width, progressBitmap.height)
        bgDst = RectF(left, top, width - left, height - top)

        setOnTouchListener { _, event ->
            if (!heShuiActivity.isReady || heShuiActivity.xView.state == XView.State.DakaIng){
                return@setOnTouchListener true
            }
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    for ((idx, rect) in lstTouchRect.withIndex()) {
                        if (rect.contains(event.x, event.y)) {
                            selectedIdx = idx
                            selectedCallback?.selected(idx)
                            MyLog.elog("第${idx + 1}个被点击......")
                            return@setOnTouchListener true
                        }
                    }
                    MyLog.elog("没有点击到!")
                    return@setOnTouchListener true
                }
                else -> return@setOnTouchListener true
            }
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(progressBitmap, bgSrc, bgDst, paint)
        val itemSize = bgWidth / (ICON_COUNT - 1)
        for (i in 0 until ICON_COUNT) {
            val x = i * itemSize
            val bitmap = bitmapList[i]
            val touchRect = lstTouchRect[i]
            touchRect.left = bgDst.left + x - bitmap.width / 2.0f
            touchRect.top = center.y - bitmap.height / 2.0f
            touchRect.right = touchRect.left + bitmap.width
            touchRect.bottom = touchRect.top + bitmap.height
            canvas.drawBitmap(bitmap,
                    touchRect.left,
                    touchRect.top,
                    paint)

            if (selectedIdx == i) {
                val mid = (touchRect.left + touchRect.right) / 2.0f
                val mtop = touchRect.bottom + dotOyDp
//                val mright = mid + DotSize / 2.0f;
//                val mbuttom = mtop + DotSize
//                paint.color = Color.RED
//                canvas.drawRect(mid - DotSize/2.0f,mtop,mright,mbuttom,paint)
                canvas.drawBitmap(dotBitmap, mid - DotSize / 2.0f, mtop, paint)
            }
        }
    }

    fun refresh(iconStateArr: IntArray, idx: Int) {
        if (iconStateArr.size != ICON_COUNT) {
            throw RuntimeException("iconStateArr.length 和 ICON_COUNT数量不一致!")
        }
        for (i in bitmapList.indices) {
            if (iconStateArr[i] == UNCOMPLETE) {
                bitmapList[i] = uncompleteBitmap
            } else if (iconStateArr[i] == COMPLETED) {
                bitmapList[i] = completedBitmap
            } else if (iconStateArr[i] == LOCKED) {
                bitmapList[i] = lockedBitmap
            } else if (iconStateArr[i] == CURRENT_ENABLE) {
                bitmapList[i] = currentEnableBitmap
            } else {
                throw RuntimeException("unknow iconStateArr[i]:" + iconStateArr[i])
            }
        }
        selectedIdx = idx
        invalidate()
    }

    fun setSelectedListener(listener: ISelected) {
        selectedCallback = listener
    }

    private fun loadBitmap(){
        progressBitmap = BitmapMemCache.getBitmap(R.drawable.dd_heshui_progress_bg)
        uncompleteBitmap = BitmapMemCache.getBitmap(R.drawable.dd_heshui_uncomplete)
        completedBitmap = BitmapMemCache.getBitmap(R.drawable.dd_hs_completed)
        lockedBitmap = BitmapMemCache.getBitmap(R.drawable.dd_heshui_unreached)
        currentEnableBitmap = BitmapMemCache.getBitmap(R.drawable.dd_hs_current_enable)
        dotBitmap = BitmapMemCache.getBitmap(R.drawable.dd_dot_1)
    }
}